package com.techcity;

import org.apache.hadoop.hive.ql.exec.UDAF;
import org.apache.hadoop.hive.ql.exec.UDAFEvaluator;

public class Sum extends UDAF {
    public static class SumState {
        private long mCount;
        private long sum_casual;
        private long sum_registered;
        private long mSum;
    }
    public static class SumEvaluator implements UDAFEvaluator{
        SumState state;
        public SumEvaluator(){
            super();
            state = new SumState();
            init();
        }
        /**
         * init函数类似于构造函数，用于UDAF的初始化
         */
        @Override
        public void init() {
            state.mCount=0;
            state.mSum = 0;
            state.sum_casual=0;
            state.sum_registered=0;
        }

        /**
         * iterate接收传入的参数，并进行内部的轮转。其返回类型为boolean * * @param o * @return
         */

        public boolean iterate(long a,long b,long c) {
            if (c!=0) {
                state.sum_casual += a;
                state.sum_registered += b;
                state.mSum += c;
                state.mCount++;
            }
            return true;
        }

        /**
         * terminatePartial无参数，其为iterate函数遍历结束后，返回轮转数据， * terminatePartial类似于hadoop的Combiner * * @return
         */
        public SumState terminatePartial(){
            return state.mCount == 0 ? null : state;
        }

        /**
         * merge接收terminatePartial的返回结果，进行数据merge操作，其返回类型为boolean * * @param o * @return
         */
        public boolean merge(SumState sumState){
            if(sumState!=null){
                state.mCount += sumState.mCount;
                state.mSum += sumState.mSum;
                state.sum_casual+=sumState.sum_casual;
                state.sum_registered +=sumState.sum_registered;
            }
            return true;
        }

        /**
         * terminate返回最终的聚集函数结果 * * @return
         */
        public String terminate() {
            return state.mCount == 0 ? null : state.sum_casual+" "+state.sum_registered+" "+state.mSum;
        }
    }

}
